package net.sppan.base.controller.business;

import net.sppan.base.common.JsonResult;
import net.sppan.base.controller.BaseController;
import net.sppan.base.entity.business.Device;
import net.sppan.base.entity.business.Purchase;
import net.sppan.base.service.IDeviceService;
import net.sppan.base.service.IPurchaseService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统计
 */
@Controller
@RequestMapping("/business/statistic")
public class StatisticController extends BaseController {

    @Autowired
    private IPurchaseService purchaseService;

    @Autowired
    private IDeviceService deviceService;

    @RequestMapping(value = { "/", "/index" })
    public String index() {
        return "business/statistic/index";
    }


    @RequestMapping(value = {"/list"})
    @ResponseBody
    public Page<Purchase> list(@RequestParam(value = "searchText", required = false) String searchText) {

        Page<Purchase> page = purchaseService.findAll(getPageRequest());
        return page;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap map) {
        return "business/purchase/form";
    }

    @RequestMapping(value= {"/edit"},method = RequestMethod.POST)
    @ResponseBody
    public JsonResult edit(Purchase purchase, ModelMap map){
        try {


            Device device = deviceService.find(purchase.getDeviceId().intValue());

            purchase.setDeviceName(device.getDeviceName());
            purchase.setTotalPrice(purchase.getUsualPrice()*purchase.getPurchaseNum());
            purchaseService.save(purchase);

        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delete(@PathVariable Integer id, ModelMap map) {
        try {
            purchaseService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }
}
